<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>雷兽互动官网-后台管理系统</title>
    <link rel="icon" href="/img/favicon.ico" />
    <link rel="stylesheet" href="/static/plugin/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/index.css">
    <style>
        .container {
            margin-top: 100px;
            margin-bottom: 200px;
        }

        @media (min-width: 576px) {
            .modal-dialog {
                max-width: 1000px;
                margin: 1.75rem auto;
            }
        }

        .control_img {
            width: 100px;
            cursor: pointer;
        }

        #banner_prodId .col {
            text-align: center;
        }

        #banner_prodId img {
            margin: 10px 0;
        }
        .jumbotron{
            border-radius: unset;
        }
        .nav-item .active{
            background-color: #E9ECEF !important;
            border-color:#E9ECEF !important;
        }
    </style>
</head>

<body>
    <div id="form_box" class="container">
        <ul class="nav nav-tabs" id="myTab" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home"
                    aria-selected="true">Banner</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab"
                    aria-controls="profile" aria-selected="false">新闻</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab"
                    aria-controls="contact" aria-selected="false">产品</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" id="contact2-tab" data-toggle="tab" href="#contact2" role="tab"
                    aria-controls="contact2" aria-selected="false">招聘</a>
            </li>
        </ul>
        <div class="tab-content" id="myTabContent">
            <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
                <div class="jumbotron">
                    <p class="lead">
                        Banner
                        <button type="button " class="btn btn-primary" id="submitBanner">提交</button>
                        <span style="color:red">*如果产品id不存在或者为空，则轮播对应的该条banner不会显示</span>
                    <form id="banner_prodId">
                        <div class="form-row">
                            <div class="col">
                                <label for="b1">Banner1 对应产品的 id</label>
                                <input type="text" class="form-control" name="b1" placeholder="B1 对应产品 id">
                                <img src="" alt="" class="control_img">
                            </div>
                            <div class="col">
                                <label for="b2">Banner2 对应产品的 id</label>
                                <input type="text" class="form-control" name="b2" placeholder="B2 对应产品 id">
                                <img src="" alt="" class="control_img">
        
                            </div>
                            <div class="col">
                                <label for="b3">Banner3 对应产品的 id</label>
                                <input type="text" class="form-control" name="b3" placeholder="B3 对应产品 id">
                                <img src="" alt="" class="control_img">
        
                            </div>
                            <div class="col">
                                <label for="b4">Banner4 对应产品的 id</label>
                                <input type="text" class="form-control" name="b4" placeholder="B4 对应产品 id">
                                <img src="" alt="" class="control_img">
        
                            </div>
                            <div class="col">
                                <label for="b5">Banner5 对应产品的 id</label>
                                <input type="text" class="form-control" name="b5" placeholder="B5 对应产品 id">
                                <img src="" alt="" class="control_img">
        
                            </div>
                            <div class="col">
                                <label for="b6">Banner6 对应产品的 id</label>
                                <input type="text" class="form-control" name="b6" placeholder="B6 对应产品 id">
                                <img src="" alt="" class="control_img">
        
                            </div>
                        </div>
                    </form>
                    </p>
                    <hr class="my-4">
                    <form id="banner_form">
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner1" >
                            <label class="custom-file-label" for="banner1" data-browse="Banner1">Banner1</label>
                        </div>
        
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner2" >
                            <label class="custom-file-label" for="banner2" data-browse="Banner2">Banner2</label>
                        </div>
        
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner3" >
                            <label class="custom-file-label" for="banner3" data-browse="Banner3">Banner3</label>
                        </div>
        
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner4" >
                            <label class="custom-file-label" for="banner4" data-browse="Banner4">Banner4</label>
                        </div>
        
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner5" >
                            <label class="custom-file-label" for="banner5" data-browse="Banner5">Banner5</label>
                        </div>
        
                        <img src="" alt="" class="control_img">
                        <div class="custom-file" style="margin-bottom: 1rem;">
                            <input type="file" class="custom-file-input" id="banner6" >
                            <label class="custom-file-label" for="banner6" data-browse="Banner6">Banner6</label>
                        </div>
        
                    </form>
                </div>
            </div>
            <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">
                <div class="jumbotron">
                    <p class="lead">
                        新闻
                        <button type="button " class="btn btn-primary" data-toggle="modal" data-target="#newsModal"
                            data-type="release">发布</button>
                    </p>
                    <hr class="my-4">
                    <table class="table  table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">发布日期</th>
                                <th scope="col">标题</th>
                                <th scope="col">封面</th>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody class="newsTbody">
                        </tbody>
                    </table>
                    <div class="modal fade" id="newsModal" tabindex="-1" role="dialog" aria-labelledby="newsModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="newsModalLabel">新闻</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form id="news_form">
                                        <div class="form-group">
                                            <label for="newTitle">新闻标题</label>
                                            <input type="text" class="form-control" id="newTitle">
                                        </div>
                                        <div class="form-group">
                                            <label for="newAbstract">新闻摘要</label>
                                            <input type="text" class="form-control" id="newAbstract">
                                        </div>
                                        <div class="custom-file" style="margin-bottom: 1rem;">
                                            <input type="file" class="custom-file-input" id="newsCover" >
                                            <label class="custom-file-label" for="newsCover" data-browse="新闻封面">新闻封面</label>
                                        </div>
                                        <div class="form-group">
                                            <label for="isTop">是否置顶</label>
                                            <div class="custom-control custom-radio custom-control-inline">
                                                <input type="radio" id="isTop" name="isTop" class="custom-control-input">
                                                <label class="custom-control-label" for="isTop">是</label>
                                            </div>
                                            <div class="custom-control custom-radio custom-control-inline">
                                                <input type="radio" id="isTop2" name="isTop" checked
                                                    class="custom-control-input">
                                                <label class="custom-control-label" for="isTop2">否</label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="newsContent">新闻内容</label>
                                            <textarea id="newsContent"></textarea>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="releaseNews">发布</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
                <div class="jumbotron">
                    <p class="lead">
                        产品
                        <button type="button " class="btn btn-primary" data-toggle="modal" data-target="#prodModal"
                            data-type="release">发布</button>
                    </p>
                    <hr class="my-4">
                    <table class="table  table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col">id</th>
                                <th scope="col">权重</th>
                                <th scope="col">产品标题</th>
                                <th scope="col">产品图片</th>
                                <th scope="col">产品二维码</th>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody class="prodTbody">
        
                        </tbody>
                    </table>
                    <div class="modal fade" id="prodModal" tabindex="-1" role="dialog" aria-labelledby="prodModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="prodModalLabel">产品</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form id="prod_form">
                                        <div class="form-group">
                                            <label for="prodTitle">产品标题</label>
                                            <input type="text" class="form-control" id="prodTitle">
                                        </div>
                                        <div class="form-group">
                                            <label for="prodDesc">产品描述</label>
                                            <input type="text" class="form-control" id="prodDesc">
                                        </div>
                                        <div class="form-group">
                                            <label for="prodWeight">权重</label>
                                            <input type="text" class="form-control" id="prodWeight">
                                        </div>
                                        <div class="custom-file" style="margin-bottom: 1rem;">
                                            <input type="file" class="custom-file-input" id="prodImg" >
                                            <label class="custom-file-label" for="prodImg" data-browse="产品图片">产品图片</label>
                                        </div>
                                        <div class="custom-file" style="margin-bottom: 1rem;">
                                            <input type="file" class="custom-file-input" id="prodQrCode" >
                                            <label class="custom-file-label" for="prodQrCode" data-browse="产品二维码">产品二维码</label>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="releaseProd">发布</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="contact2" role="tabpanel" aria-labelledby="contact2-tab">
                <div class="jumbotron">
                    <p class="lead">
                        招聘
                        <button type="button " class="btn btn-primary" data-toggle="modal" data-target="#recruitModal"
                            data-type="release">发布</button>
                    </p>
                    <hr class="my-4">
                    <table class="table  table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">发布日期</th>
                                <th scope="col">职位</th>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody class="recruitTbody">
                        </tbody>
                    </table>
                    <div class="modal fade" id="recruitModal" tabindex="-1" role="dialog" aria-labelledby="recruitModalLabel"
                        aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="recruitModalLabel">招聘</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body">
                                    <form id="recruit_form">
                                        <div class="form-group">
                                            <label for="recruitName">职位名称</label>
                                            <input type="text" class="form-control" id="recruitName">
                                        </div>
                                        <div class="form-group">
                                            <label for="recruitContent">招聘详情</label>
                                            <textarea id="recruitContent"></textarea>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary" id="releaseRecruit">发布</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="fade_box">
            <div class="fade_content"></div>
            <div class="fade_bg"></div>
        </div>
    </div>


</body>
<script src="/static/plugin/jquery/index.js" type="text/javascript"></script>
<script src="/static/plugin/popper/index.js" type="text/javascript"></script>
<script src="/static/plugin/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="/static/plugin/tinymce/tinymce.min.js"></script>
<script>
    $(function () {
        let news_textImgs = [];//新闻富文本中的文件id数组
        let prod_params = {};
        let news_params = {};
        tinymce.init({
            selector: '#newsContent',
            height: 800,
            branding: false,
            language: 'zh_CN',
            content_style: "img {max-width:900px;} p {margin: 0px; border:0px ; padding: 0px;}",
            plugins: 'code lineheight print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
            toolbar: 'fullscreen preview code lineheight image | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | alignleft aligncenter alignright alignjustify | undo redo | forecolor backcolor | bold italic underline strikethrough | link media charmap anchor pagebreak codesample | ltr rtl',
            toolbar_drawer: 'sliding',
            file_picker_types: 'media',
            paste_data_images: true,
            images_upload_handler: function (blobInfo, succFun, failFun) {
                var xhr, formData;
                var file = blobInfo.blob();//转化为易于理解的file对象
                xhr = new XMLHttpRequest();
                xhr.withCredentials = true;
                xhr.open('POST', '/api/textImg');
                xhr.onload = function () {
                    var json;
                    if (xhr.status != 200) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.result.src != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    news_textImgs.push(json.result.id)
                    succFun(json.result.src);
                };
                formData = new FormData();
                formData.append('file', file, file.name);//此处与源文档不一样
                xhr.send(formData);
            },
            init_instance_callback: function (editor) {
            }
        });
        tinymce.init({
            selector: '#recruitContent',
            height: 450,
            branding: false,
            content_style: "p {margin: 0px; border:0px ; padding: 0px;}",
            language: 'zh_CN',
            plugins: 'code lineheight print preview fullscreen paste searchreplace save autosave link autolink  table codesample lists advlist hr charmap anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
            toolbar: 'fullscreen preview code lineheight | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link  charmap anchor pagebreak codesample | ltr rtl',
            toolbar_drawer: 'sliding',
        });

        //解决弹出框中tinymce无法focus的bug
        $(document).on('focusin', function(e) {
            if ($(e.target).closest(".tox").length) {
                e.stopImmediatePropagation();
            }
        });
        //产品图片上传  
        $("#prodImg").change(res => {
            var formData = new FormData();
            let $dom = $('#prodImg')
            formData.append('file', $dom[0].files[0]); //添加图片信息的参数
            $.ajax({
                url: "/api/fileImg",
                type: "post",
                dataType: "json",
                cache: false,
                data: formData,
                processData: false, // 不处理数据
                contentType: false, // 不设置内容类型
                success: function (res) {
                    if (res.code != 200) {
                        alert(res.msg);
                    } else {
                        $dom.next().text(res.result.title)
                        prod_params.prodImg = res.result.id
                    }
                    $dom[0].value = ""
                }
            })
        })
        //产品二维码上传
        $("#prodQrCode").change(res => {
            var formData = new FormData();
            let $dom = $('#prodQrCode')
            formData.append('file', $dom[0].files[0]); //添加图片信息的参数
            $.ajax({
                url: "/api/fileImg",
                type: "post",
                dataType: "json",
                cache: false,
                data: formData,
                processData: false, // 不处理数据
                contentType: false, // 不设置内容类型
                success: function (res) {
                    if (res.code != 200) {
                        alert(res.msg);
                    } else {
                        $dom.next().text(res.result.title)
                        prod_params.prodQrCode = res.result.id
                    }
                    $dom[0].value = ""
                }
            })
        })
        //新闻封面上传 
        $("#newsCover").change(res => {
            var formData = new FormData();
            let $dom = $('#newsCover')
            formData.append('file', $dom[0].files[0]); //添加图片信息的参数
            $.ajax({
                url: "/api/fileImg",
                type: "post",
                dataType: "json",
                cache: false,
                data: formData,
                processData: false, // 不处理数据
                contentType: false, // 不设置内容类型
                success: function (res) {
                    if (res.code != 200) {
                        alert(res.msg);
                    } else {
                        $dom.next().text(res.result.title)
                        news_params.coverId = res.result.id
                    }
                    $dom[0].value = ""
                }
            })
        })

        function renderNews() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: 'get',
                    url: "/api/getNews?page=0&limit=10000",
                    success: function (res) {
                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                        if (res.code == 200) {
                            let dom = ``
                            res.result = res.result || []
                            res.result.sort((i, v) => { return v.isTop - i.isTop })
                            res.result.forEach((item, index) => {
                                dom += `
                        <tr >
                            <th scope="row">${index + 1}${item.isTop == 1 ? `<span class="badge badge-secondary">置顶</span>` : ""}</th>
                            <td>${item.releaseDate}</td>
                            <td>${item.title}</td>
                            <td>
                                <img src="${item.coverSrc}" alt=""  class="control_img">
                            </td>
                            <td>
                                <button type="button"  class="btn btn-primary postNews" data-toggle="modal" data-target="#newsModal"  data-type="edit" >修改</button>  
                                <button type="button"  class="btn btn-danger delNews" data-id="${item.id}">删除</button>  
                            </td>
                        </tr>
                        `
                            })
                            $(".newsTbody").html(dom)
                            //点击事件赋值数据
                            let postNews = $(".postNews")
                            for (i in postNews) {
                                $(".postNews").eq(i).attr("data-res", JSON.stringify(res.result[i]))
                            }
                            //删除新闻
                            $(".delNews").click(function () {
                                if (!confirm("确认删除？")) { return }
                                let id = $(this).data("id")
                                $.ajax({
                                    type: 'post',
                                    url: "/api/delNews",
                                    data: { id },
                                    success: function (res) {
                                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                                        if (res.code == 200) {
                                            alert("删除成功")
                                            renderNews()
                                        } else {
                                            alert("删除失败:" + res.msg)
                                        }
                                    }
                                })
                            })
                            resolve()
                        } else {
                            reject()
                        }
                    }
                })
            })
        }

        $('#newsModal').on('show.bs.modal', function (event) {
            news_params = {}
            $("#isTop2")[0].checked = true
            var button = $(event.relatedTarget) // Button that triggered the modal
            var type = button.data('type')
            if (type == 'edit') {
                var editData = button.data('res')
                //表单回显
                $("#releaseNews").text("修改")
                $("#newTitle").val(editData.title)
                $("#newAbstract").val(editData.abstract)
                $("#newsCover").next().text(editData.cover)
                tinymce.get('newsContent').setContent(editData.content);
                editData.isTop == 1 && ($("#isTop")[0].checked = true);
                news_textImgs = editData.textImgs ? editData.textImgs.split(",") : [];
                //修改新闻
                $("#releaseNews").unbind().click(() => {
                    let params = {
                        title: $("#newTitle").val(),
                        abstract:$("#newAbstract").val(),
                        content: tinymce.get('newsContent').getContent(),
                        text: tinymce.get('newsContent').getContent({ format: 'text' }),
                        id: editData.id,
                        coverId: news_params.coverId || editData.coverId,
                        delId: editData.coverId,
                        isTop: $("#isTop")[0].checked ? 1 : 0,
                        textImgs:news_textImgs.join(),
                    }
                    if (!params.title || !params.content || !params.coverId) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        type: 'post',
                        url: '/api/editArticle',
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }
                            if (res.code == 200) {
                                alert("修改成功")
                                $('#newsModal').modal('hide')
                                renderNews()
                            } else {
                                alert("修改失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            } else if (type == 'release') {
                //清空表单
                $("#releaseNews").text("发布")
                $("#news_form")[0].reset()
                $("#newsCover").next().text("")
                news_textImgs = [];
                //发布新闻
                $("#releaseNews").unbind().click(() => {
                    let params = {
                        title: $("#newTitle").val(),
                        abstract:$("#newAbstract").val(),
                        content: tinymce.get('newsContent').getContent(),
                        text: tinymce.get('newsContent').getContent({ format: 'text' }),
                        coverId: news_params.coverId,
                        isTop: $("#isTop")[0].checked ? 1 : 0,
                        textImgs:news_textImgs.join(),
                    }
                    if (!params.title || !params.content || !params.coverId) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        type: 'post',
                        url: '/api/article',
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }

                            if (res.code == 200) {
                                alert("发布成功")
                                $('#newsModal').modal('hide')
                                renderNews()
                            } else {
                                alert("发布失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            }
        })

        function renderProd() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: 'get',
                    url: "/api/getProduct?page=0&limit=10000",
                    success: function (res) {
                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                        if (res.code == 200) {
                            let dom = ``
                            res.result = res.result || []
                            res.result.forEach((item, index) => {
                                dom += `
                        <tr >
                            <th scope="row">${item.id}</th>
                            <td>${item.weight}</td>
                            <td>${item.title}</td>
                            <td>
                                <img src="${item.imgSrc}" alt="" class="control_img">
                            </td>
                            <td>
                                <img src="${item.qrSrc}" alt=""  class="control_img">
                            </td>
                            <td>
                                <button type="button "  class="btn btn-primary postProd" data-toggle="modal" data-target="#prodModal" data-type="edit">修改</button> 
                                <button type="button"  class="btn btn-danger delProd" data-id="${item.id}">删除</button>   
                            </td>
                        </tr>
                        `
                            })
                            $(".prodTbody").html(dom)
                            let postProd = $(".postProd")
                            for (i in postProd) {
                                $(".postProd").eq(i).attr("data-res", JSON.stringify(res.result[i]))
                            }

                            //删除产品
                            $(".delProd").click(function () {
                                if (!confirm("确认删除？")) { return }
                                let id = $(this).data("id")
                                $.ajax({
                                    type: 'post',
                                    url: "/api/delProd",
                                    data: { id },
                                    success: function (res) {
                                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                                        if (res.code == 200) {
                                            alert("删除成功")
                                            renderProd()
                                        } else {
                                            alert(`删除失败:` + res.msg)
                                        }
                                    }
                                })
                            })
                            resolve()
                        } else {
                            reject()
                        }
                    }
                })
            })

        }

        $('#prodModal').on('show.bs.modal', function (event) {
            prod_params = {}
            var button = $(event.relatedTarget) // Button that triggered the modal
            var type = button.data('type')
            if (type == 'edit') {
                var editData = button.data('res')
                //表单回显
                $("#releaseProd").text("修改")
                $("#prodTitle").val(editData.title)
                $("#prodDesc").val(editData.desc)
                $("#prodWeight").val(editData.weight),
                    $("#prodImg").next().text(editData.img)
                $("#prodQrCode").next().text(editData.qrcode)
                //修改产品
                $("#releaseProd").unbind().click(() => {
                    let params = {
                        prodTitle: $("#prodTitle").val(),
                        prodDesc: $("#prodDesc").val(),
                        prodWeight: $("#prodWeight").val(),
                        prodImg: prod_params.prodImg || editData.imgId,
                        prodQrCode: prod_params.prodQrCode || editData.qrcodeId,
                        id: editData.id,
                        delImgId: editData.imgId,
                        delQrId: editData.qrcodeId,
                    }
                    if (!params.prodTitle || !params.prodImg || !params.prodQrCode) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        url: "/api/editProd",
                        type: "post",
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }

                            if (res.code == 200) {
                                alert("修改成功")
                                $('#prodModal').modal('hide')
                                renderProd()
                            } else {
                                alert("修改失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            } else if (type == 'release') {
                //清空表单
                $("#releaseProd").text("发布")
                $("#prod_form")[0].reset()
                $("#prodImg").next().text("")
                $("#prodQrCode").next().text("")
                //发布产品
                $("#releaseProd").unbind().click(() => {
                    let params = {
                        prodTitle: $("#prodTitle").val(),
                        prodDesc: $("#prodDesc").val(),
                        prodWeight: $("#prodWeight").val(),
                        prodImg: prod_params.prodImg,
                        prodQrCode: prod_params.prodQrCode,
                    }
                    if (!params.prodTitle || !params.prodImg || !params.prodQrCode) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        url: "/api/product",
                        type: "post",
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }
                            if (res.code == 200) {
                                alert("发布成功")
                                $('#prodModal').modal('hide')
                                renderProd()
                            } else {
                                alert("发布失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            }
        })


        function renderBanner() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: 'get',
                    url: "/api/getBanner",
                    success: function (res) {
                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                        if (res.code == 200) {
                            let $inputAll = $("#banner_prodId").find(".form-control")
                            let $bInput = $("#banner_form").find(".custom-file-input")
                            res.result = res.result || []
                            res.result.forEach((item, index) => {
                                $inputAll.eq(index).val(item.prodId)
                                $inputAll.eq(index).next().attr("src", `${item.prodSrc}`)
                                $bInput.eq(index).next().text(item.title)
                                $bInput.eq(index).parent().prev().attr("src", `${item.src}`)
                            })
                            resolve()
                        } else {
                            reject()
                        }

                    }
                })
            })

        }

        $("#submitBanner").click(function () {
            let arr = $("#banner_prodId").serializeArray()
            console.log(arr);
            let formArr = arr.map(item => {
                return item.value || 0
            })
            console.log(formArr);
            let params = {
                formStr: formArr.join(",")
            }
            $.ajax({
                type: "post",
                url: "/api/postBannerProd",
                data: params,
                success: function (res) {
                    if (res.code == -2) { window.location.href = "/admin/login.html" }
                    if (res.code == 200) {
                        alert("提交成功")
                        renderBanner()
                    } else {
                        alert("提交失败,err=" + res.msg)
                    }
                }
            })
        })

        //上传banner
        let bInput = $("#banner_form").find(".custom-file-input")
        for (let i = 0; i < bInput.length; i++) {
            bInput.eq(i).change(function () {
                var formData = new FormData();
                formData.append('file', bInput.eq(i)[0].files[0]); //添加图片信息的参数
                $.ajax({
                    type: "post",
                    url: `/api/banner?id=${i + 1}`,
                    dataType: "json",
                    cache: false,
                    data: formData,
                    processData: false, // 不处理数据
                    contentType: false, // 不设置内容类型
                    success: function (res) {
                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                        if (res.code != 200) {
                            alert(res.msg);
                        } else {
                            renderBanner()
                        }
                    }
                })
            })
        }



        function checkLogin(resolve, reject) {
            $.ajax({
                type: "get",
                url: "/api/checkLogin",
                success: function (res) {
                    if (res.code == -2) {
                        reject()
                    }
                    resolve()
                }
            })
        }

        //渲染招聘
        function renderRecruit() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: 'get',
                    url: "/api/getRecruit",
                    success: function (res) {
                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                        if (res.code == 200) {
                            let dom = ``
                            res.result = res.result || []
                            res.result.forEach((item, index) => {
                                dom += `
                                <tr >
                                    <th scope="row">${index + 1}</th>
                                    <td>${item.releaseDate}</td>
                                    <td>${item.position}</td>
                                    <td>
                                        <button type="button"  class="btn btn-primary postRecruit" data-toggle="modal" data-target="#recruitModal"  data-type="edit" >修改</button>  
                                        <button type="button"  class="btn btn-danger delRecruit" data-id="${item.id}">删除</button>  
                                    </td>
                                </tr>
                                `
                            })
                            $(".recruitTbody").html(dom)
                            //点击事件赋值数据
                            let postRecruit = $(".postRecruit")
                            for (i in postRecruit) {
                                $(".postRecruit").eq(i).attr("data-res", JSON.stringify(res.result[i]))
                            }
                            //删除招聘
                            $(".delRecruit").click(function () {
                                if (!confirm("确认删除？")) { return }
                                let id = $(this).data("id")
                                $.ajax({
                                    type: 'post',
                                    url: "/api/delRecruit",
                                    data: { id },
                                    success: function (res) {
                                        if (res.code == -2) { window.location.href = "/admin/login.html" }
                                        if (res.code == 200) {
                                            alert("删除成功")
                                            renderRecruit()
                                        } else {
                                            alert("删除失败:" + res.msg)
                                        }
                                    }
                                })
                            })
                            resolve()
                        } else {
                            reject()
                        }
                    }
                })
            })
        }

        $('#recruitModal').on('show.bs.modal', function (event) {
            news_params = {}
            var button = $(event.relatedTarget) // Button that triggered the modal
            var type = button.data('type')
            if (type == 'edit') {
                var editData = button.data('res')
                //表单回显
                $("#releaseRecruit").text("修改")
                $("#recruitName").val(editData.position)
                tinymce.get('recruitContent').setContent(editData.content);
                //修改新闻
                $("#releaseRecruit").unbind().click(() => {
                    let params = {
                        position: $("#recruitName").val(),
                        content: tinymce.get('recruitContent').getContent(),
                        id: editData.id
                    }
                    if (!params.position || !params.content) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        type: 'post',
                        url: '/api/editRecruit',
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }
                            if (res.code == 200) {
                                alert("修改成功")
                                $('#recruitModal').modal('hide')
                                renderRecruit()
                            } else {
                                alert("修改失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            } else if (type == 'release') {
                //清空表单
                $("#releaseRecruit").text("发布")
                $("#recruit_form")[0].reset()
                //发布新闻
                $("#releaseRecruit").unbind().click(() => {
                    let params = {
                        position: $("#recruitName").val(),
                        content: tinymce.get('recruitContent').getContent(),
                    }
                    if (!params.position || !params.content) {
                        alert("表单未填写完")
                        return
                    }
                    $.ajax({
                        type: 'post',
                        url: '/api/postRecruit',
                        data: params,
                        success: function (res) {
                            if (res.code == -2) { window.location.href = "/admin/login.html" }

                            if (res.code == 200) {
                                alert("发布成功")
                                $('#recruitModal').modal('hide')
                                renderRecruit()
                            } else {
                                alert("发布失败，原因:" + res.msg)
                            }
                        }
                    })
                })
            }
        })

        /* 
        
        //获取新闻
            renderNews()
            //获取产品
            renderProd()
            //获取banner信息
            renderBanner()
         */

        //登录态校验
        let p0 = new Promise((resolve, reject) => {
            //检查登录
            checkLogin(resolve, reject)
        }).then(() => {
            Promise.all([renderNews(), renderProd(), renderBanner(), renderRecruit()]).then(() => {
                $(".control_img").click(function () {
                    let $src = $(this).attr("src")
                    let dom = `
                        <div class="card" style="width:562px;height:auto">
                            <img src="${$src}" style="width:100%" />
                        </div>
                    `;
                    $(".fade_content").html(dom)

                    $(".fade_bg").click(function () {
                        $(".fade_box").fadeOut(300)
                    })
                    $(".fade_box").fadeIn(300)
                    $(".fade_content").css({
                        "left": `calc(50% - 280px)`,
                        "top": "10%"
                    })
                })
            })

        }).catch(() => {
            window.location.href = "/admin/login.html"
        })


    })
</script>

</html>